package com.example.demo.net;

import com.example.demo.base.MyApplication;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.MemoryCookieStore;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okgo.request.PostRequest;
import okhttp3.OkHttpClient;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

public class HttpManager {
    public static final String mBaseUrl = "https://api.apiopen.top/getJoke?page=1&count=2&type=video";

    private HttpManager() {
        init();
    }

    public static HttpManager getInstance() {
        return SingleTon.sInstance;
    }

    private static final class SingleTon {
        public static final HttpManager sInstance = new HttpManager();
    }

    private void init() {
        HttpHeaders headers = new HttpHeaders();
        HttpParams params = new HttpParams();

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        // log相关
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        loggingInterceptor.setColorLevel(Level.INFO);
        builder.addInterceptor(loggingInterceptor);
        // 超时时间设置，默认60秒
        builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
        builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);

        // 使用数据库保持cookie，如果cookie不过期，则一直有效
        builder.cookieJar(new CookieJarImpl(new MemoryCookieStore()));
        // 其他统一的配置
        OkGo.getInstance().init(MyApplication.getsInstance())
                .setOkHttpClient(builder.build())
                .setCacheMode(CacheMode.NO_CACHE)
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)
                .setRetryCount(3)
                .addCommonHeaders(headers)
                .addCommonParams(params);
    }

    public  GetRequest get() {
        return OkGo.get(mBaseUrl);
    }

    public PostRequest post() {
        return OkGo.post(mBaseUrl);
    }

}
